package com.pijunn.users

import grails.plugins.springsecurity.Secured;

import org.grails.plugin.jcaptcha.JcaptchaService

import com.pijunn.common.MailingAddress
import com.pijunn.security.SecRole;
import com.pijunn.security.SecUserSecRole;

class ProfileController {

	/** dependency injection for spring security */
	def	springSecurityService

	/** dependency injection for the password encoder */
	def passwordEncoder

	/** dependency injection for the profile service */
	def profileService

	def userRole = SecRole.findByAuthority('ROLE_USER')
		
	def confirm = { Long id ->
		def user = AppUser.findByCreateTime(new Date(id))
		user.enabled = true
		if (user.save([flush: true])) {
			springSecurityService.reauthenticate user.username
	        flash.message = message(code: 'appUser.created.message')
	        redirect(controller: "LabeledItem", action: "create")
		}
		else {
			user.errors.reject("Problem Activating user.  Please contact support.")
			[appUserInstance: user]
		}
	}
	
	def passwordExpired = {
		session['SAVED_REQUEST'] = '/labeledItem/create'
		[username: session['SPRING_SECURITY_LAST_USERNAME']]
	 }

	
	def updatePassword(String password, String password_new, String password_new_2) {
	   String username = session['SPRING_SECURITY_LAST_USERNAME']
	   if (!username) {
		  flash.message = 'Sorry, an error has occurred'
		  redirect controller: 'login', action: 'auth'
		  return
	   }
	   
	   //String password = params.password
	   //String newPassword = params.password_new
	   //String newPassword2 = params.password_new_2
	   if (!password || !password_new || !password_new_2 || password_new != password_new_2) {
		   flash.message = 'Please enter your current password and a valid new password'
		   render view: 'passwordExpired', model: [username: session['SPRING_SECURITY_LAST_USERNAME']]
		   return
	   }
	
	   AppUser user = AppUser.findByUsername(username.decodeHTML())
	   if (!passwordEncoder.isPasswordValid(user.password, password, null /*salt*/)) {
		   flash.message = 'Current password is incorrect'
		   render view: 'passwordExpired', model: [username: session['SPRING_SECURITY_LAST_USERNAME']]
		   return
	   }
	
	   if (passwordEncoder.isPasswordValid(user.password, password_new, null /*salt*/)) {
		   flash.message = 'Please choose a different password from your current one'
		   render view: 'passwordExpired', model: [username: session['SPRING_SECURITY_LAST_USERNAME']]
		   return
	   }
	
	   user.password = password_new
	   user.passwordExpired = false
	   user.save() // if you have password constraints check them here
	
	   springSecurityService.reauthenticate(username.decodeHTML(), password_new)
	   
	   redirect(url: session['SAVED_REQUEST'] ?: '/')
	}

    @Secured(['ROLE_USER','ROLE_ADMIN'])
	def show() {
		def user = springSecurityService.currentUser
		
		log.info(user)
        def appUserInstance = AppUser.get(user.id)
        if (!appUserInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'appUser.label', default: 'AppUser'), id])
            redirect(action: "list")
            return
        }

        render(view: 'show', model: [appUserInstance: user])
    }
	
	def edit = {
		[appUserInstance: springSecurityService.currentUser, confirmEMail: springSecurityService.currentUser.contactEMail, addressInstance: new MailingAddress()]
	}
	
	def save = {
	
		AppUser u = springSecurityService.currentUser
		u.properties = params
		
		u.createTime = new Date()
		def hasErrors = false
		
		if (u.contactEMail != params.confirmEMail) {
			u.errors.rejectValue("contactEMail", "appUser.email.mismatch")
			hasErrors = true
		}
		
		if (hasErrors) {
			render(view:'edit', model: [appUserInstance: u, confirmEMail: params.confirmEMail, addressInstance: new MailingAddress()])
			return
		}
		
		if (!u.save(flush: true)) {
			render(view:'edit', model: [appUserInstance: u, confirmEMail: params.confirmEMail, addressInstance: new MailingAddress()])
			return
		}
		
		flash.message = message(code: 'appUser.updated.message')
		redirect(action: 'show')

	}

}
